package com.liang.security.springmvc.service.impl;

import com.liang.security.springmvc.model.AuthenticationRequest;
import com.liang.security.springmvc.model.UserDto;
import com.liang.security.springmvc.service.AuthenticationService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author liang zai
 * @date 2021/8/31 10:44
 * @description
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    /**
     * 用户认证，校验用户身份信息是否合法
     *
     * @param request 用户认证请求，账号和密码
     * @return 认证成功的用户信息
     */
    @Override
    public UserDto authentication(AuthenticationRequest request) {
        //校验参数是否为空
        if (request == null || StringUtils.isEmpty(request.getUsername()) || StringUtils.isEmpty(request.getPassword())) {
            throw new RuntimeException("账号或密码为空");
        }
        //根据账号去查询数据库,这里测试程序采用模拟方法
        UserDto userDto = getUserDto(request.getUsername());
        if (userDto == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!request.getPassword().equals(userDto.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        return userDto;
    }

    /**
     * 根据账号获取用户信息
     * @param username
     * @return
     */
    private UserDto getUserDto(String username) {
        return userMap.get(username);
    }

    /**
     * 用户信息
     */
    public Map<String, UserDto> userMap = new HashMap<>();
    {
        Set<String> authorities1 = new HashSet<>();
        authorities1.add("p1");//这个p1我们人为让它和/r/r1对应

        Set<String> authorities2 = new HashSet<>();
        authorities2.add("p2");//这个p2我们人为让它和/r/r2对应
        userMap.put("dada",new UserDto("1001","dada","123456","张晓晓","7737377",authorities1));
        userMap.put("xixi",new UserDto("1001","xixi","123456","张无忌","7737377",authorities2));
    }
}
